// Vue 组合式适配器，连接用例与组件

import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { loginUseCase, wxchatLoginUseCase } from "@/useCases/login/login.js";
import { LoginApiGateway } from "./LoginApiGateway.js";
// import { OrganizateApiGateway } from "@/adapters/organizationalStructure/organizate/OrganizateApiGateway.js";
import { useUserStore } from "@/store/user.js";
import { message } from 'ant-design-vue';
// import { permissionTotalList } from '@/utils/staticData.js';
// import { usePermissionsStore } from '@/store/permissions.js';
// const permissionsStore = usePermissionsStore();
import { useDevice } from '@/hooks/useDevice';
const { isMobile } = useDevice();


// 实例化具体接口（外层细节）
const gateway = new LoginApiGateway();
// const organizateGateway = new OrganizateApiGateway();

// 调用用例（内层用例不感知 Vue）
const loginHttp = loginUseCase(gateway);
const wxchatLoginHttp = wxchatLoginUseCase(gateway);
// 暴露给组件的响应式数据和方法（数据转换在此层完成）
export function useLoginAddAdapter() {
  const router = useRouter();
  const userStore = useUserStore();
  const loginForm = ref({ 
    userName: '',
    passWord: '' 
  });
  let wxCode = ref(''); // 微信code微信code
  // 手机号弹框相关
  const phoneModalVisible = ref(false);
  const userId = ref('');
  const redirect_uri = ref('https://admin.zkbaice.cn/login');
  // const isProd = ref(import.meta.env.PROD ? true : false);
  const isProd = ref(false);


  // 退出登录方法
  const logout = () => {
    const origin = window.location.origin;
    window.location.href = `${origin}/login`;
  };

  const goRoute = (list) => {
    const item = list[0];
    if(item.children && (item.children.length > 0)) {
      goRoute(item.children);
    } else {
      router.push(item.path);
    }
  }
  const goRoute1 = (list) => {
    const item = list[0];
    if(item.children && (item.children.length > 0)) {
      goRoute(item.children);
    } else {
      window.location.href = `${redirect_uri.value}/${item.path}`;
    }
  }
  
  // 登录
  const submitForm = async (values) => {
    const params = { username: values.userName, password: values.passWord };
    await loginHttp(params).then(async(res) => {
      userStore.accessToken = res.accessToken;
      userStore.refreshToken = res.refreshToken;
      userStore.userInfo = res.user;
      
      // if(res.user?.type === 'admin'){
      //   let permissions = [];
      //   permissionTotalList.map(item => permissions.push(item.value))
      //   userStore.permissions = permissions;
      //   const list = permissionsStore.getMenuList();
      //   permissionsStore.dynamicRoutes();
      //   goRoute(list);
      // } else {
      //   userStore.permissions = res.permissions.flat(Infinity);
      //   const list = permissionsStore.getMenuList();
      //   permissionsStore.dynamicRoutes();
      //   if(list && list.length > 0){
      //     goRoute(list)
      //   } else {
      //     router.push('/404');
      //   }
      // }
      message.success('登录成功!');
    })
  };
  // 微信授权web登录
  const authorizeWeb = () => {
    const encodedByEncodeURI = encodeURIComponent(redirect_uri.value);
    const login_type = 'CorpApp';
    const appid = 'wwdc6b75526d823fe2';
    const AGENTID = '1000125';
    const authUrl = `https://login.work.weixin.qq.com/wwlogin/sso/login?login_type=${login_type}&appid=${appid}&redirect_uri=${encodedByEncodeURI}&agentid=${AGENTID}&state=WWLogin`;
    window.location.href = authUrl;
  }
  // 微信授权app登录
  const authorizeApp = () => {
    const encodedByEncodeURI = encodeURIComponent(redirect_uri.value);
    const scope = 'snsapi_privateinfo';
    const appid = 'wwdc6b75526d823fe2';
    const AGENTID = '1000125';
    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodedByEncodeURI}&response_type=code&scope=${scope}&state=STATE&agentid=${AGENTID}#wechat_redirect`;
    window.location.href = authUrl;
  }
  // 发送微信code给后端
  const sendWxWorkCodeWeb =() => {
    const params = {
      code: wxCode.value
    };
    wxchatLoginHttp(params).then((res) => {
      userStore.accessToken = res.accessToken;
      userStore.refreshToken = res.refreshToken;
      userStore.userInfo = res.user;
      // if(res.user?.type === 'admin'){
      //   let permissions = [];
      //   permissionTotalList.map(item => permissions.push(item.value))
      //   userStore.permissions = permissions;
      //   const list = permissionsStore.getMenuList();
      //   permissionsStore.dynamicRoutes();
      //   goRoute1(list);
      // } else {
      //   userStore.permissions = res.permissions.flat(Infinity);
      //   const list = permissionsStore.getMenuList();
      //   permissionsStore.dynamicRoutes();
      //   if(list && list.length > 0){
      //     goRoute1(list)
      //   } else {
      //     router.push('/404');
      //   }
      // }
    }).catch(() => {
      logout();
    })
  };
  // 获取微信code
  const getWxCode = () => {
    const urlParams = new URLSearchParams(window.location.search);
    console.log(urlParams, 'urlParams');
    wxCode.value = urlParams.get('code');
    console.log(wxCode.value, 'wxCode.value');
    if(!wxCode.value) {
      if(isMobile.value) {
        authorizeApp();
      } else {
        authorizeWeb();
      }
    } else {
      sendWxWorkCodeWeb();
    }
  }
  onMounted(() => {
    if(isProd.value) {
      getWxCode();
    }
  });
  return {
    loginForm,
    submitForm,
    phoneModalVisible,
    userId,
    logout,
    isProd,
  };
}